﻿using System;
using System.Text;

namespace TeaLightV5.Foundation.Utilities
{
    public class UrlCreator
    {
        private readonly StringBuilder _url = new StringBuilder();
        private bool _hasParameter;

        public UrlCreator()
        {
            _hasParameter = false;
        }

        public UrlCreator(string url)
        {
            _url.Append(url);
            _hasParameter = url.Contains("?");
        }

        public UrlCreator(Uri uri)
        {
            string url = uri.ToString();
            _url.Append(url);
            _hasParameter = url.Contains("?");
        }

        public void Add(string name, object value)
        {
            if (value == null)
            {
                return;
            }
            if (_hasParameter)
            {
                _url.Append("&");
            }
            else
            {
                _url.Append("?");
                _hasParameter = true;
            }
            _url.Append(name);
            _url.Append("=");
            _url.Append(Convert(value));
        }

        private string Convert(object value)
        {
            if (value is bool)
            {
                bool b = (bool)value;
                if (b)
                {
                    return "1";
                }
                return "0";
            }
            // HttpUtility.UrlEncode(value.ToString());
            // todo
            return value.ToString();
        }

        public Uri ToUri(UriKind uriKind)
        {
            return new Uri(_url.ToString(), uriKind);
        }


        public Uri ToUri()
        {
            return new Uri(_url.ToString());
        }

        public override string ToString()
        {
            return _url.ToString();
        }
    }
}
